import json

from myapp import models
from myapp.utils import getPublicData


def getPageData():
    jobs = getPublicData.getAllJobs()
    typeData = []
    for j in jobs:
        typeData.append(j.type)
    return list(set(typeData))


def getBarData(jobType):
    if jobType == 'all':
        jobs = models.JobInfo.objects.all()
    else:
        jobs = models.JobInfo.objects.filter(type=jobType).all()

    natureData = {}
    for j in jobs:
        if natureData.get(j.companyNature, -1) == -1:
            natureData[j.companyNature] = 1
        else:
            natureData[j.companyNature] += 1

    nutureList = list(sorted(natureData.items(), key=lambda x: x[1], reverse=True))
    # print(nutureList)   # [('互联网', 9), ('计算机软件', 4)]

    rowData = []
    columnData = []
    for k, v in nutureList:
        rowData.append(k)
        columnData.append(v)

    return rowData, columnData

def getPieData(jobType):
    if jobType == 'all':
        jobs = models.JobInfo.objects.all()
    else:
        jobs = models.JobInfo.objects.filter(type=jobType).all()

    data = {}
    for j in jobs:
        if data.get(j.address, -1) == -1:
            data[j.address] = 1
        else:
            data[j.address] += 1

    result = []
    for k, v in data.items():
        result.append({
            'name': k,
            'value': v
        })

    return result[:40]


def getAreaData(jobType):
    if jobType == 'all':
        jobs = models.JobInfo.objects.all()
    else:
        jobs = models.JobInfo.objects.filter(type=jobType).all()

    def mapFn(item):
        item.companyPeople = json.loads(item.companyPeople)[1]
        return item

    jobs = list(map(mapFn, jobs))
    data = [0 for i in range(6)]
    for j in jobs:
        p = j.companyPeople
        if p <= 20:
            data[0] += 1
        elif p <= 100:
            data[1] += 1
        elif p <= 500:
            data[2] += 1
        elif p <= 1000:
            data[3] += 1
        elif p < 10000:
            data[4] += 1
        else:
            data[5] += 1

    return data, getPublicData.peopleList
